package com.trytry.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.jdbc.Work;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.transform.Transformers;
import org.hibernate.type.IntegerType;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.SqlQuery;

public class CommonDaoImpl implements CommonDao {
	@Autowired 
private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public int findall(String hql) {
		return this.getCurrentSession().createQuery(hql).list().size();
	}

	@Override
	public List getDatas(String hql, int start, int limit) {
		return this.getCurrentSession().createQuery(hql).setFirstResult(start)   
		        .setMaxResults(limit).list();
	}
	
	@Override
	public List getSQLDatas(String sql, int start, int limit,String EntityName,String keywords) throws HibernateException, ClassNotFoundException {
		String[] keyword=keywords.split(" ");
		if(keywords!=null&&keywords.trim().length()!=0){
			for(int i=0;i<keyword.length;i++){
			sql+=" and title like ?";
			}
		}
		SQLQuery sqlquery=this.getCurrentSession().createSQLQuery(sql);
		if(keywords!=null&&keywords.trim().length()!=0){
			for(int i=0;i<keyword.length;i++){
			sqlquery.setString(i,"%"+keyword[i]+"%");
			}
			}
		List list=sqlquery.addEntity(EntityName).setFirstResult(start).setMaxResults(limit).list();
		return list;
	}

	@Override
	public Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public int sqlfindall(String sql,String keywords) {
		String[] keyword=keywords.split(" ");
		if(keywords!=null&&keywords.trim().length()!=0){
			for(int i=0;i<keyword.length;i++){
			sql+=" and title like ?";
			}
		}
		SQLQuery sqlquery=this.getCurrentSession().createSQLQuery(sql);
		if(keywords!=null&&keywords.trim().length()!=0){
			for(int i=0;i<keyword.length;i++){
			sqlquery.setString(i,"%"+keyword[i]+"%");
			}
			}
		return (Integer) sqlquery.addScalar("rowcount",new IntegerType()).uniqueResult();
	}

}
